<?php
namespace api\common\models;
use yii\db\Query;
use yii\web\ServerErrorHttpException;
use yii\data\Pagination;
use yii\web\Link;
use yii\db\ActiveRecord;
class test extends ActiveRecord{

    public static $_tableName = '{{%comment_app}}' ;

    /**
     * @return array|string
     */
    public static function tableName()
    {
        return self::$_tableName;
    }


    /*
     * 获取列表
     * @param $id
     * @param $catid
     * @param $pid 上级id
     * @return array|\yii\db\ActiveRecord[]
     */
    public function getList($content_id)
    {
        self::$_tableName = self::tableExists(self::formatTable($content_id, \Yii::$app->params['table_comment']['num'], \Yii::$app->params['table_comment']['table']));

        $query = new Query();
        $query->from(self::$_tableName.' as a');
        $query->select('a.*,b.head_img,b.username');
        $query->leftJoin('{{%user_app}} as b','a.uid = b.id');
        //$query->where(['a.content_id'=>$content_id,'a.catid'=>$catid,'a.pid'=>$pid]);
        $query->where('a.`status` =1 and a.content_id='.$content_id.' and a.catid='.$catid.' and (a.pid='.$pid.' or a.comment_id = '.$pid.')');
        $count = $query->count();
        $pagination = new Pagination(['totalCount' => $count]);
        $pagination->defaultPageSize = \Yii::$app->params['page_size'];
        $data = $query->offset($pagination->offset)
            ->limit($pagination->limit)
            ->orderBy('a.time asc')
            ->all();


        $this->serializePagination($pagination);
        $pagination->defaultPageSize = \Yii::$app->params['page_size'];

        $_data = [];
        $_data['items'] = $data;
        $_data['_links'] = $this->linksEnvelope;
        $_data['_meta'] = $this->metaEnvelope;
        return $_data;
    }

    public function serializePagination($pagination)
    {
        $this->linksEnvelope = Link::serialize($pagination->getLinks(true));
        $this->metaEnvelope = [
            'totalCount' => $pagination->totalCount,
            'pageCount' => $pagination->getPageCount(),
            'currentPage' => $pagination->getPage() + 1,
            'perPage' => $pagination->getPageSize(),
        ];
    }

    /*
     * 分表使用动态计算表名称 根据id区间计算
     * @param $id
     * @param int $num
     * @param $tablename
     */
    public static function formatTable($id,$num=10000,$tablename){
        if($id==''){
            throw new ServerErrorHttpException('由于不明原因未能计算数据表.');
        }
        $suffix = \Yii::$app->db->tablePrefix.$tablename.'_'.(ceil($id/$num)*$num);
        return $suffix;
    }


    /*
 * 查找表是否存在 不存在则创建
 * @param $table
 */
    public static function tableExists($tableName){
        $db = \Yii::$app->db;
        if($db->createCommand("SHOW TABLES LIKE '".$tableName."'")->queryAll()==null)
        {
            $sql = <<<EOT
CREATE TABLE $tableName (
  `comment_id` int(11) NOT NULL AUTO_INCREMENT,
  `pid` int(11) NOT NULL DEFAULT '0' COMMENT '回复的评论id ',
  `content_id` int(11) NOT NULL COMMENT '内容id',
  `catid` int(11) NOT NULL COMMENT '分类id',
  `uid` int(11) NOT NULL COMMENT '用户id',
  `username` varchar(50) NOT NULL,
  `content` varchar(900) NOT NULL COMMENT '评论内容',
  `time` datetime NOT NULL COMMENT '评论时间',
  `like` int(11) NOT NULL COMMENT '点赞数',
  `comment` int(11) DEFAULT '0' COMMENT '评论数',
  `status` tinyint(1) DEFAULT '0' COMMENT '是否通过审核 0:未通过 1:通过',
  PRIMARY KEY (`comment_id`),
  KEY `catid` (`catid`),
  KEY `content_id` (`content_id`)
) ENGINE=MyISAM AUTO_INCREMENT=12 DEFAULT CHARSET=utf8 COMMENT='评论接口表';
EOT;
            ;
            $db->createCommand($sql)->execute();
        }

        return $tableName;
    }
}